<template>
  <div class="flow">
    <div class="formLook">
      <div class="main">

      <TitleComponent title="用人需求申请" />
        <DemandInfo
          ref="childFormRef"
          :neekWorksForm="neekWorksForm"
          :neekWorksFormRules="neekWorksFormRules"
          :formSize="formSize"
          @dept-change="requireDeptIdChange"
          :buIdOptions="buIdOptions"
          :hr-name-options="hrNameOptions"
        ></DemandInfo>
        <!-- 岗位信息 -->
        <div class="needNotes">
          <div class="title_line">
            <div class="title_img">
              <img src="@/assets//images/post.png" alt="" />
            </div>
            <p class="title">岗位信息</p>
          </div>
          <div>
            <div class="job-container">
              <div class="add-job">
                <span class="add-btn">+</span>
                <span @click="handleOpenDialog()">添加岗位</span>
              </div>
            </div>
            <el-tabs
              v-model="activeTab"
              type="card"
              class="demo-tabs"
              editable
              @edit="handleTabsEdit"
              @tab-click="handleTabClick"
            >
              <template #add-icon> 添加岗位 </template>
              <el-tab-pane
                v-for="(item, index) in editableTabs"
                :key="item.name"
                :label="`岗位${index + 1}`"
                :name="item.name"
              >
                <el-form
                  :ref="jobRef(item.name)"
                  :model="neekWorksForm.jobPostDetailDtoList[Number(item.name)]"
                  :rules="neekWorksFormRules"
                  label-width="auto"
                  class="demo-neekWorksForm"
                  :size="formSize"
                  status-icon
                  label-position="top"
                >
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="岗位名称" prop="jobName">
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].jobName
                          "
                          placeholder="请输入岗位名称"
                          type="textarea"
                          :autosize="{ minRows: 1, maxRows: 2 }"
                          maxlength="100"
                          show-word-limit
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="招聘类型" prop="recruitmentType">
                        <el-select
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].recruitmentType
                          "
                          clearable
                          placeholder="请选择招聘类型"
                        >
                          <el-option
                            v-for="item in sys_recruitment_type"
                            :key="item.value"
                            :label="item.label"
                            :value="Number(item.value)"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="岗位性质" prop="jobNature">
                        <el-select
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].jobNature
                          "
                          clearable
                          placeholder="请选择岗位性质"
                        >
                          <el-option
                            v-for="item in sys_job_nature"
                            :key="item.value"
                            :label="item.label"
                            :value="Number(item.value)"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="职级" prop="positionLevel">
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].positionLevel
                          "
                          placeholder="请输入职级"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="薪酬范围" prop="salaryRange">
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].salaryRange
                          "
                          placeholder="请输入薪酬范围"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <!-- 工作年限  学历 -->
                  <el-row :gutter="24">
                    <el-col :span="24">
                      <el-form-item prop="jobResponsibilities">
                        <!-- 自定义 label -->
                        <template #label>
                          <span style="display: flex; align-items: center">
                            <span>岗位职责</span>
                            <el-tooltip
                              placement="right"
                              trigger="click"
                              popper-class="successTip"
                              style="margin-left: 5px"
                            >
                              <template #content>
                                <div class="tooltipText">
                                  <div class="textOne">
                                    已规避岗位不清晰的用工风险！
                                  </div>
                                  <div class="textTwo">
                                    如果用人单位没有制定明确的录用条件，那么很有可能
                                  </div>
                                  <div class="textTwo">
                                    会对日后以“员工在试用期间被证明不符合录用条件”
                                  </div>
                                  <div class="textTwo">
                                    为由解除劳动合同带来麻烦。
                                  </div>
                                </div>
                              </template>
                              <img src="@/assets//images/check.png" alt="" />
                            </el-tooltip>
                          </span>
                        </template>
                        <!-- 表单项内容 -->
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].jobResponsibilities
                          "
                          type="textarea"
                          :rows="4"
                          maxlength="1000"
                          show-word-limit
                          placeholder="请输入岗位职责"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="24">
                      <el-form-item label="任职条件" prop="qualification">
                        <!-- 自定义 label -->
                        <template #label>
                          <span style="display: flex; align-items: center">
                            <span>任职条件</span>
                            <el-tooltip
                              placement="right"
                              trigger="click"
                              popper-class="successTip"
                            >
                              <template #content>
                                <div class="tooltipText">
                                  <div class="textTwo">
                                    招聘简章或广告中常见的歧视性内容包括：民族歧视、
                                  </div>
                                  <div class="textTwo">
                                    种族歧视、性别歧视、农村劳动者、残疾人和传染病病
                                  </div>
                                  <div class="textTwo">
                                    原携带者等。用人单位在招聘过程中不要在招聘简章或
                                  </div>
                                  <div class="textTwo">
                                    广告中出现法律禁止的相关歧视性内容，用人单位依法
                                  </div>
                                  <div class="textTwo">
                                    享有用人自主权，但应当向劳动者提供平等的就业机会，
                                  </div>
                                  <div class="textTwo">
                                    不要发布歧视性的招聘信息。
                                  </div>
                                </div>
                              </template>
                              <img src="@/assets//images/error.png" alt="" />
                            </el-tooltip>
                          </span>
                        </template>
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].qualification
                          "
                          type="textarea"
                          :rows="4"
                          maxlength="1000"
                          show-word-limit
                          placeholder="请输入任职条件"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="24">
                      <el-form-item label="岗位关键词" prop="jobKeywords">
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].jobKeywords
                          "
                          :rows="4"
                          type="textarea"
                          maxlength="1000"
                          show-word-limit
                          placeholder="请输入岗位关键词"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="24">
                      <el-form-item label="岗位信息描述文件" prop="file">
                        <Upload
                          v-model:modelValue="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].file
                          "
                          :isShowTip="false"
                          :fileType="fileType"
                          @update:modelValue="uploadFiles"
                          @delete="handleFileDelete"
                        ></Upload>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="需求人数" prop="requirePersonNumber">
                        <el-input
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].requirePersonNumber
                          "
                          maxlength="1000"
                          show-word-limit
                          placeholder="请输入需求人数"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="需求紧急程度"
                        prop="requireEmergencyLevel"
                      >
                        <div
                          class="tags"
                          :class="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].requireEmergencyLevel == 0
                              ? 'primaryTag'
                              : 'normalTag'
                          "
                          @click="onChange1(item, index)"
                        >
                          <el-button
                            v-if="false"
                            v-model="
                              neekWorksForm.jobPostDetailDtoList[
                                Number(item.name)
                              ].requireEmergencyLevel
                            "
                          ></el-button
                          >一般
                        </div>
                        <div
                          class="tags"
                          :class="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].requireEmergencyLevel == 1
                              ? 'warningTag'
                              : 'normalTag'
                          "
                          @click="onChange2(item, index)"
                        >
                          <el-button
                            v-if="false"
                            v-model="
                              neekWorksForm.jobPostDetailDtoList[
                                Number(item.name)
                              ].requireEmergencyLevel
                            "
                          ></el-button
                          >紧急
                        </div>
                        <div
                          class="tags"
                          :class="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].requireEmergencyLevel == 2
                              ? 'dangerTag'
                              : 'normalTag'
                          "
                          @click="onChange3(item, index)"
                        >
                          <el-button
                            v-if="false"
                            v-model="
                              neekWorksForm.jobPostDetailDtoList[
                                Number(item.name)
                              ].requireEmergencyLevel
                            "
                          ></el-button
                          >非常紧急
                        </div>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="期望到岗日期" prop="hopeArrivalTime">
                        <el-date-picker
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].hopeArrivalTime
                          "
                          type="date"
                          placeholder="年/月/日"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="截止日期" prop="closeTime">
                        <el-date-picker
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].closeTime
                          "
                          type="date"
                          placeholder="年/月/日"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="24">
                    <el-col :span="6">
                      <el-form-item label="是否是特殊岗位">
                        <el-radio-group
                          @change="changeRadios"
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].isSpecialPosition
                          "
                        >
                          <el-radio value="0" size="large">是</el-radio>
                          <el-radio value="1" size="large">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col
                      v-if="
                        neekWorksForm.jobPostDetailDtoList[Number(item.name)]
                          .isSpecialPosition == 0
                      "
                      :span="18"
                    >
                      <el-form-item
                        label="岗位资格证明要求"
                        prop="specialJobRequirements"
                      >
                        <el-input
                          type="textarea"
                          v-model="
                            neekWorksForm.jobPostDetailDtoList[
                              Number(item.name)
                            ].specialJobRequirements
                          "
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <!-- *岗位资格证明要求 如果是否是特殊岗位选择：是，则出现此字段并手工填写，文本域，1000字，必填。 -->
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <!-- 岗位库选择 -->
        <NeedWorksDialog
          :needWorksDialog="openDialog"
          ref="openRef"
          @ok="handleOk"
          @cancel="handleCancel"
          :existingIds="existingIds"
        />
        <div class="btns">
          <div class="back-btn">
            <el-button type="primary" @click="handleSubmit">提交需求</el-button>
            <el-button class="btn-css" @click="handleSave">保存</el-button>
            <el-button class="btn-css" @click="$GoBack()">关闭</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import TitleComponent from "@/components/TitleComponent.vue";
import { searchDepyList } from "@/api/recruitment/jobApplication/index.js";
import {
  newNeedWorkers,
  seachPersonList,
  needWorkersView,
} from "@/api/recruitment/needWorkers/index.js";
import { formatDate } from "@/utils/index.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import Upload from "@/components/FileUpload/index.vue";
import { reactive, onMounted, ref } from "vue";
import useUserStore from "@/store/modules/user.js";
import NeedWorksDialog from "@/views/recruitment/needWorkers/components/needWorksDialog.vue";
import { flowableTodo } from "@/api/flowableApi/flowableApi.js";
import DemandInfo from "../components/DemandInfo.vue";
// 子组件引用
const openRef = ref(null);
const childFormRef = ref(null);
const activeTab = ref(0);
const editableTabs = ref([]);
const existingIds = ref([]);
// 岗位信息库弹窗
const openDialog = ref(false);
const user = useUserStore().user;
const route = useRoute();
const { proxy } = getCurrentInstance();
const fileType = ref([
  "doc",
  "xls",
  "ppt",
  "txt",
  "pdf",
  "docx",
  "xlsx",
  "pptx",
]);

const formSize = ref("default");
const { sys_recruitment_type } = proxy.useDict("sys_recruitment_type");
const { sys_job_nature } = proxy.useDict("sys_job_nature");
const buIdOptions = reactive([]);
// hr

const hrNameOptions = reactive([]);
const neekWorksFormRules = reactive({
  requireJobOverview: [
    { required: true, message: "请输入岗位需求描述", trigger: "blur" },
  ],
  requireProposerName: [
    {
      required: true,
      message: "请选择需求申请人",
      trigger: "change",
    },
  ],
  requireDeptId: [
    {
      required: true,
      message: "请选择需求部门",
      trigger: "blur",
    },
  ],
  proposeTime: [
    {
      required: true,
      message: "请输入申请时间",
      trigger: "blur",
    },
  ],
  hrId: [
    {
      required: true,
      message: "请选择HR",
      trigger: "blur",
    },
  ],
  jobName: [
    {
      required: true,
      message: "请输入岗位名称",
      trigger: "blur",
    },
  ],
  recruitmentType: [
    {
      required: true,
      message: "请选择招聘类型",
      trigger: "blur",
    },
  ],
  salaryRange: [
    {
      required: true,
      message: "请输入薪资范围",
      trigger: "blur",
    },
  ],
  jobNature: [
    {
      required: true,
      message: "请选择岗位性质",
      trigger: "blur",
    },
  ],
  jobResponsibilities: [
    {
      required: true,
      message: "请输入岗位职责",
      trigger: "blur",
    },
  ],
  qualification: [
    {
      required: true,
      message: "请输入任职条件",
      trigger: "blur",
    },
  ],
  jobKeywords: [
    {
      required: true,
      message: "请输入岗位关键词",
      trigger: "blur",
    },
  ],
  requireEmergencyLevel: [
    {
      required: true,
      message: "请选择需求紧急程度",
      trigger: "blur",
    },
  ],
  requirePersonNumber: [
    {
      required: true,
      message: "请输入需求人数",
      trigger: "blur",
    },
  ],
  hopeArrivalTime: [
    {
      required: true,
      message: "请选择期望到岗时间",
      trigger: "blur",
    },
  ],
  closeTime: [
    {
      required: true,
      message: "请选择期截至时间",
      trigger: "blur",
    },
  ],
  specialJobRequirements: [
    {
      required: true,
      message: "请输入岗位资格证明要求",
      trigger: "blur",
    },
  ],
});
const editableTabsValue = ref("1"); // 默认值设置为 '1'
const handleTabClick = (tab) => {
  console.log(tab, "tabtab");
  const tabIndex = parseInt(tab.index) + 1;
  editableTabsValue.value = tabIndex;
};
const neekWorksForm = reactive({
  delflag: 0, //删除标志位默认为0可以不传
  demandJobs: "" /*需求岗位数量 0单个 1多个*/,
  hrId: "", //hr的id
  hrName: "", //hr的名字
  id: "", //用人需求表主键id
  //添加岗位数据
  jobPostDetailDtoList: [],
  processId: "", //流程实例id
  proposeTime: "", //申请日期
  requireDeptId: "", //需求部门id
  requireDeptName: "", //需求部门name
  requireJobOverview: "", //岗位需求概述
  requireProposerCode: "",
  requireProposerId: user.userId, //需求申请人id
  requireProposerName: user.userName, //需求申请人name
  status: "", //* 审批状态1草稿 2审批中 1000审批完成 201退回修改
  type: "" /*0保存修改  1提交 */,
});
// 新增岗位
const handleTabsEdit = (targetName, action) => {
  if (action == "add") {
    // 按照标签页顺序添加
    const newTabName = editableTabs.value.length + 1;
    editableTabs.value.push({
      title: `岗位${Number(newTabName)}`,
      name: newTabName,
      content: "新岗位内容",
    });
    activeTab.value = newTabName;
    neekWorksForm.jobPostDetailDtoList[newTabName] = {
      closeTime: "", //截至日期
      delFlag: 0, //删除标志位1删除 0未删除
      file: "", //文件
      hopeArrivalTime: "", //期望到达日期
      id: "", //岗位信息表主键id
      isSpecialPosition: "0", //是否是特殊岗位
      jobCode: "", //岗位编码
      jobId: "", //岗位id
      jobKeywords: "", //岗位关键词
      jobName: "", //岗位名称
      jobResponsibilities: "", //岗位职责
      positionLevel: "", //职级
      qualification: "", //任职条件
      recruitmentType: "",
      jobNature: "", //岗位性质
      requireEmergencyLevel: 0, //需求紧急程度
      requireJobId: "", //用人需求表主键id
      requirePersonNumber: "", //需求人数
      salaryRange: "", //薪酬范围
      specialJobRequirements: "", //特殊岗位要求
      // hopeInterviewMethod: ""
    };
  } else if (action == "remove") {
    const tabs = editableTabs.value;
    let activeName = activeTab.value;
    if (activeName == targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name == targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        }
      });
    }

    activeTab.value = activeName;
    editableTabs.value = tabs.filter((tab) => tab.name != targetName);
    delete neekWorksForm.jobPostDetailDtoList[targetName];
  }
};

const jobRef = (index) => {
  return "neekWorksFormRef" + index;
};

onMounted(() => {
  getDemandDetailsList();
  seachPersonsList();
  // 获取编辑数据
  if (route.query.edit == "1" && route.query.id) {
    getEditNeedWork();
  } else {
    neekWorksForm.proposeTime = formatDate(new Date()).dates;
  }
});
// 是否是特殊岗位
const changeRadios = (val) => {
  console.log(
    "changeRadios",
    neekWorksForm.jobPostDetailDtoList[activeTab.value].isSpecialPosition
  );
};

// 部门
const requireDeptIdChange = (val) => {
  buIdOptions.forEach((item) => {
    if (val == item.value) {
      neekWorksForm.requireDeptName = item.label;
    }
  });
};
const seachPersonsList = async () => {
  // HR
  const res1 = await seachPersonList({
    roleKey: "HR",
  });
  if (res1.rows.length > 0) {
    res1.rows.map((item) => {
      let label = item.userName;
      let value = item.userId;
      hrNameOptions.push({
        label,
        value,
      });
    });
  }
};
const getDemandDetailsList = async () => {
  // 搜索部门
  const { data } = await searchDepyList();

  if (data.length > 0) {
    data.map((item) => {
      let label = item.deptName;
      let value = item.deptId;
      buIdOptions.push({
        label,
        value,
      });
    });
  }
};
// 紧急程度切换
const onChange1 = (item, index) => {
  neekWorksForm.jobPostDetailDtoList[item.name].requireEmergencyLevel = 0;
};

const onChange2 = (item, index) => {
  neekWorksForm.jobPostDetailDtoList[item.name].requireEmergencyLevel = 1;
};

const onChange3 = (item, index) => {
  neekWorksForm.jobPostDetailDtoList[item.name].requireEmergencyLevel = 2;
};
const resetForm = () => {
  // 重置第一个表单
  childFormRef.value.resetFields();
  // 重置其他所有表单
  editableTabs.value.forEach((item) => {
    const refName = jobRef(item.name);
    if (proxy.$refs[refName] && proxy.$refs[refName][0]) {
      proxy.$refs[refName][0].resetFields();
    }
  });
  neekWorksForm.jobPostDetailDtoList.forEach((item) => {
    for (let key in item) {
      if (item.hasOwnProperty(key)) {
        item[key] = ""; // 将所有字段设置为空字符串
      }
    }
  });
  // 清空 editableTabs
  editableTabs.value = [];
};

// 编辑数据
const getEditNeedWork = async () => {
  const res = await needWorkersView(route.query.id);
  Object.keys(res.data).forEach((item) => {
    if (res.data[item] && item != "jobPostDetailVoList") {
      neekWorksForm[item] = res.data[item];
    }
  });
  editableTabs.value = []; // 清空现有的 editableTabs
  neekWorksForm.jobPostDetailDtoList = {}; // 清空现有的 jobPostDetailDtoList
  // 排序
  if (res.data.jobPostDetailVoList && res.data.jobPostDetailVoList.length > 0) {
    res.data.jobPostDetailVoList.sort((a, b) => {
      return a.id - b.id;
    });
    // 回显数据标签页
    res.data.jobPostDetailVoList.forEach((item, index) => {
      const newTabName = index + 1;
      editableTabs.value.push({
        title: `岗位${index + 1}`,
        name: newTabName,
        content: "岗位内容",
        id: item.id,
      });
      neekWorksForm.jobPostDetailDtoList[newTabName] = item;
    });
    //设置默认选中的标签为第一个标签
    activeTab.value = 1;
    if (res.data.processId) {
      // procInsId.value = res.data.processId;
      init(res.data.processId);
    }
  }
};
// 附件
const uploadFiles = (files) => {
  neekWorksForm.jobPostDetailDtoList[activeTab.value].file = files;
};
const handleFileDelete = (updatedFiles) => {
  // userInfoForm.saveTransferFileVos=updatedFiles;
  neekWorksForm.jobPostDetailDtoList[activeTab.value].file = updatedFiles;
};
const init = async (processId) => {
  let params = {
    owner: user.userId,
    role: user.userId,
    flowKey: "RECRUIT_DEMAND",
  };

  const todoRes = await flowableTodo(processId, params);
  if (todoRes.data.length > 0) {
    // 审批
    flowableBtns.value = JSON.parse(todoRes.data[0].description)[0].btns;

    flowableTodoData.value = todoRes.data[0];
    taskId.value = todoRes.data[0].taskId;
  }
};

// 保存
const message = (text) => {
  ElMessageBox.confirm(`是否要${text}这条用人需求申请?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 深拷贝 neekWorksForm 并修改时间格式
      const neekWorksFormCopy = JSON.parse(JSON.stringify(neekWorksForm));
      neekWorksFormCopy.jobPostDetailDtoList = Object.values(
        neekWorksFormCopy.jobPostDetailDtoList
      ).map((item) => {
        if (item) {
          item.hopeArrivalTime = formatDate(item.hopeArrivalTime).dates;
          item.closeTime = formatDate(item.closeTime).dates;
          item.requirePersonNumber = Number(item.requirePersonNumber);
        }
        return item;
      });
      neekWorksFormCopy.jobPostDetailDtoList =
        neekWorksFormCopy.jobPostDetailDtoList.filter((item) => item !== null);
      // neekWorksFormCopy 的其他数据
      if (text == "保存") {
        neekWorksFormCopy.type = 0;
        neekWorksFormCopy.status = 1;
      } else if (text == "提交") {
        neekWorksFormCopy.type = 1;
        neekWorksFormCopy.status = 2;
        neekWorksFormCopy.taskId = route.query.taskId;
      }
      // 多岗位数量
      neekWorksFormCopy.demandJobs =
        neekWorksFormCopy.jobPostDetailDtoList.length;
      neekWorksFormCopy.flowKey = "RECRUIT_DEMAND";
      newNeedWorkers(neekWorksFormCopy).then((res) => {
        if (res.code == 200) {
          ElMessage({
            type: "success",
            message: `${text}成功`,
          });
          proxy.$GoBack();
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

// 岗位库弹窗
const handleOpenDialog = (index) => {
  if (openRef.value) {
    existingIds.value = Object.values(neekWorksForm.jobPostDetailDtoList).map(
      (item) => item.id
    );
    console.log(existingIds, "existingIds");

    openRef.value.clearTableSelection(); // 正确方式：通过 .value 访问子组件实例
  }
  openDialog.value = true;
};
// 选择岗位
const handleOk = (selectValue) => {
  openDialog.value = false;

  if (selectValue.value.length === 0) {
    ElMessage({
      type: "warning",
      message: "请选择至少一个岗位",
    });
    return;
  }
  selectValue.value.forEach((selectedItem, index) => {
    //新对象
    const selectedJob = Object.assign({}, selectedItem);
    console.log("selectedJob", editableTabs, selectedJob);
    // 生成新的标签名称
    const newTabName = editableTabs.value.length + 1;
    // 添加新的标签页
    editableTabs.value.push({
      title: `岗位${newTabName}`,
      name: newTabName,
      content: "新岗位内容",
      id: selectedJob.id,
    });
    let newIndex = editableTabs.value.length;
    // 设置当前选中的标签页为新添加的标签页
    activeTab.value = newTabName;
    editableTabsValue.value = newIndex;
    // 岗位的数据独立
    neekWorksForm.jobPostDetailDtoList[newTabName] = selectedJob;
    neekWorksForm.jobPostDetailDtoList[newTabName].jobId = selectedJob.id;
  });
};
// 关闭岗位弹窗
const handleCancel = () => {
  openDialog.value = false;
};
// 校验方法
const validateFun = async (val) => {
  // 先验证主表单
  try {
    await childFormRef.value.validate();
  } catch (error) {
    // 显示第一个验证错误信息
    const firstError = Object.values(error)[0][0];
    // ElMessage.error(firstError.message);
    
    // 滚动到主表单区域（修复：使用更精确的选择器）
    const mainFormElement = document.querySelector('.DemandInfo');
    if (!mainFormElement) {
      const mainFormElement = document.querySelector('.formLook .el-form');
      if (mainFormElement) {
        mainFormElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    } else {
      mainFormElement.scrollIntoView({ behavior: 'smooth', block: 'start' });

    }
    
    return; // 停止进一步的验证
  }

  //主表单验证
  let firstInvalidTabIndex = -1;
  const validationPromises = editableTabs.value.map((item, index) => {
    const refName = jobRef(item.name);
    return new Promise((resolve) => {
      if (proxy.$refs[refName] && proxy.$refs[refName][0]) {
        proxy.$refs[refName][0].validate((valid, errors) => {
          if (!valid && firstInvalidTabIndex === -1) {
            firstInvalidTabIndex = index;
            // 记录第一个错误字段
            console.log('第一个错误字段:', errors[0]?.prop);
          }
          resolve(valid);
        });
      } else {
        if (firstInvalidTabIndex === -1) {
          firstInvalidTabIndex = index;
        }
        resolve(false);
      }
    });
  });

  const allValidResults = await Promise.all(validationPromises);
  const allValid = allValidResults.every((result) => result);

  if (allValid) {
    message(val);
  } else {
    // 跳转到未通过校验的标签页
    if (firstInvalidTabIndex !== -1) {
      const invalidTab = editableTabs.value[firstInvalidTabIndex];
      activeTab.value = Number(invalidTab.name);
      
      // 等待标签页切换完成（增加等待时间）
      setTimeout(() => {
        // 定位到具体的错误字段
        const refName = jobRef(invalidTab.name);
        const formInstance = proxy.$refs[refName][0];
        
        if (formInstance && formInstance.$el) {
          // 尝试找到第一个错误字段
          const errorElement = formInstance.$el.querySelector('.el-form-item.has-error');
          
          if (errorElement) {
            // 滚动到错误字段
            errorElement.scrollIntoView({ 
              behavior: 'smooth', 
              block: 'center', 
              inline: 'nearest' 
            });
            
            // 添加高亮闪烁效果
            errorElement.classList.add('error-highlight');
            setTimeout(() => {
              errorElement.classList.remove('error-highlight');
            }, 1500);
          } else {
            // 如果找不到具体错误字段，滚动到标签页顶部
            const tabContent = document.querySelector(`.el-tabs__content .el-tab-pane[name="${invalidTab.name}"]`);
            if (tabContent) {
              tabContent.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
          }
        }
      }, 200); // 增加等待时间，确保标签页完全切换
    }
  }
};

const handleSave = async () => {
  validateFun("保存");
};
// 通过
const handleSubmit = () => {
  validateFun("提交");
};

</script>

<style lang="scss" scoped>
.main {
  padding-top: 0px !important;
  padding-bottom: 34px;
  width: 100%;
  background: #fff;
  // overflow: auto;
  border-radius: 10px;
  .needNotes {
    .title_line {
      display: flex;
      align-items: center;

      margin-bottom: 10px;

      .line {
        width: 2px;
        height: 20px;
        background: rgba(245, 154, 35);
        margin-right: 10px;
      }

      .title {
        font-size: 16px;
        font-weight: bold;
        color: rgb(102, 102, 102);
      }
    }

    .text {
      color: #fff;
      font-size: 13px;
      padding: 5px;
      height: 32px;
      width: 76px;
      line-height: 22px;
      border-radius: 4px;
      text-align: center;
    }

    .color1 {
      background: rgb(245, 154, 35);
    }

    .color2 {
      background: rgb(132, 0, 255);
    }

    .isNo {
      width: 43px;
      height: 28px;
      border-radius: 8px;
      line-height: 28px;
      text-align: center;
      color: #fff;
      margin: 0 10px;
      cursor: pointer;
    }

    .isColor {
      background: rgb(107, 202, 0);
    }

    .noColor {
      background: rgb(250, 75, 81);
    }
  }
}

:deep(.el-radio:last-child) {
  margin-right: 10px !important;
}

:deep(.el-form) {
  max-width: 100% !important;
  padding-left: 20px;
}

.btn {
  width: 30px;
  height: 30px;
  margin-left: 10px;
}

.tooltipText {
  padding: 5px;

  .textOne {
    font-size: 15px;
  }

  .textTwo {
    font-size: 14px;
    color: #fff;
    margin-top: 5px;
  }
}

.tag {
  margin-left: 10px;
}

:deep(.el-date-editor).el-input {
  width: 100% !important;
}

.noclickjob {
  background: rgba(2, 123, 245, 0.466);
}

.clickjob {
  background: rgb(64, 158, 255);
}

.tags {
  width: 68px;
  height: 28px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 10px;
  cursor: pointer;
}

.primaryTag {
  background: rgb(216, 235, 255);
  color: rgb(78, 174, 255);
  font-weight: bold;
}

.warningTag {
  background: rgb(253, 246, 236);
  color: rgb(231, 166, 68);
  font-weight: bold;
}

.dangerTag {
  background: rgb(254, 240, 240);
  color: rgb(245, 115, 115);
  font-weight: bold;
}

.normalTag {
  background: rgb(244, 244, 245);
  color: rgb(167, 169, 174);
  font-weight: bold;
}

.radios {
  height: 14px;
  width: 14px;
  background: rgb(64, 158, 255);
  border-color: rgb(64, 158, 255);
  border: 1px solid #dcdfe6;
  border-radius: 100%;
  box-sizing: border-box;
  display: inline-block;
  /* height: var(--el-radio-input-height); */
  position: relative;
  cursor: pointer;
}

.noradios {
  height: 14px;
  width: 14px;
  background: rgb(255, 255, 255);
  border-color: rgb(255, 255, 255);
  border: 1px solid #dcdfe6;
  border-radius: 100%;
  box-sizing: border-box;
  cursor: pointer;
  display: inline-block;
  /* height: var(--el-radio-input-height); */
  position: relative;
}

.radios:after {
  transform: translate(-50%, -50%) scale(1);
  background-color: white;
  border-radius: 100%;
  content: "";
  height: 4px;
  left: 50%;
  position: absolute;
  top: 50%;
  transition: transform 0.15s ease-in;
  width: 4px;
}

:deep(.el-tabs__new-tab) {
  width: 80px;
  margin: 0 !important;
  height: 40px;
  font-size: 15px;
  display: none;
}
// 提示气泡
.successTip.el-popper.is-dark {
  background-color: #eafaf0;
  border: 1px solid #33d170;
  color: #33d170;
}

// 三角形颜色
.successTip.el-popper.is-dark .el-popper__arrow:before {
  background-color: #eafaf0;
  border: 1px solid #33d170;
}

// 提示气泡
.warningTip.el-popper.is-dark {
  background-color: #fff7e5;
  border: 1px solid #ffae00;
  color: #33d170;
}

// 三角形颜色
.warningTip.el-popper.is-dark .el-popper__arrow:before {
  background-color: rgb(255, 232, 117);
  border: 1px solid rgb(255, 232, 117);
}

.el-form-item__label {
  display: flex !important;
  // align-items: flex-start;
  box-sizing: border-box;
  color: var(--el-text-color-regular);
  display: inline-flex;
  flex: 0 0 auto;
  font-size: var(--el-form-label-font-size);
  height: 32px;
  justify-content: start !important;
  text-align: left;
  line-height: 32px;
  padding: 0 12px 0 0;
}
.job-container {
  display: flex;
  align-items: center;
  gap: 10px;
  // margin-left: 10px;
}
.add-job {
  display: flex;
  align-items: center;
  border: 1px dashed #4285f4;
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
  color: #4285f4;
}

.add-btn {
  margin-right: 5px;
}

// 新增：错误字段高亮样式
.error-highlight {
  animation: highlight 1.5s ease-in-out;
}

@keyframes highlight {
  0%, 100% {
    background-color: transparent;
  }
  50% {
    background-color: rgba(255, 240, 240, 0.7);
  }
}

// 新增：确保标签页内容区域可滚动
.el-tabs__content {
  max-height: calc(100vh - 400px);
  overflow-y: auto;
}
</style>